import React, { useEffect, useState } from 'react'
import style from './Index.module.less'
import { getDetailRequest } from './ajax'
import { awaitWrap, formatDate } from '@src/assets/js/tool'
import { Skeleton } from 'antd'

async function initData (id, setContent, setTitle, setDate, setAuthor, setFiles, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getDetailRequest(id))
  setLoading(false)
  if (e === null && d !== null) {
    setContent(d.content)
    setTitle(d.title)
    setAuthor(d.author)
    if (d.file) {
      setFiles(d.file)
    }
    if (d.release_datetime) {
      setDate(formatDate(d.release_datetime, 'YYYY-MM-DD HH:mm'))
    }
  }
}

function Main ({ title, meta }) {
  const id = meta.id
  const [content, setContent] = useState('')
  const [loading, setLoading] = useState(true)
  const [t, setT] = useState('')
  const [author, setAuthor] = useState('')
  const [date, setDate] = useState('')
  const [files, setFiles] = useState([])
  useEffect(() => {
    if (id) {
      initData(id, setContent, setT, setDate, setAuthor, setFiles, setLoading)
    }
  }, [id])
  return (
    <div className={style.container}>
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <div className={style.inner}>
        <div className={style.article}>
          <Skeleton loading={loading} title>
            <div className={style.title}>{t}</div>
            {
              (date || author) && (
                <div className={style.info}>
                  {author && <span>{author}</span>}
                  <span>{date}</span>
                </div>
              )
            }
            <div dangerouslySetInnerHTML={{ __html: content }} />
            {
              files.length > 0 && (
                <div className={style.files}>
                  <div className={style['files-label']}>附件：</div>
                  <div className={style['files-value']}>
                    {
                      files.map((li, i) => {
                        return (
                          <span className={style.file} key={i}><a href={li.url} target='__blank'>{li.original_filename}</a></span>
                        )
                      })
                    }
                  </div>
                </div>
              )
            }
          </Skeleton>
        </div>
      </div>
    </div>
  )
}

export default Main
